package com.xsmart.oa.services;

import com.baomidou.mybatisplus.plugins.Page;
import com.xsmart.common.constant.ApiInfoFieldConstant;
import com.xsmart.common.constant.RedisKeyConstant;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.common.services.LoginTokenService;
import com.xsmart.common.util.RedisUtil;
import com.xsmart.oa.dao.ServiceListCtrlDao;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务列表管理
 *
 * @author guojd
 */
@Service
public class ServiceListCtrlService {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ServiceListCtrlDao serviceListCtrlDao;

    /**
     * 缓存同步api到数据库
     *
     * @param requestBean
     * @param httpServletRequest
     * @return
     */
    public ResponseBean synApiCacheToDb(RequestBean requestBean, HttpServletRequest httpServletRequest) {
        ResponseBean responseBean = requestBean.getResponseBean();
        List<String> apiList = redisUtil.getKey(RedisKeyConstant.API_INFO_PREFIX + "*");
        for (String apiKey : apiList) {
            Map<String, String> apiInfo = redisUtil.getHashByKey(apiKey);

            Map<String, Object> apiMap = new HashMap<>();
            //服务URI
            apiMap.put("service_uri", MapUtils.getString(apiInfo, ApiInfoFieldConstant.SERVICE_URI, ""));
            //服务URL
            apiMap.put("service_url", MapUtils.getString(apiInfo, ApiInfoFieldConstant.URL, ""));
            //服务模块
            apiMap.put("servcie_modular", MapUtils.getString(apiInfo, ApiInfoFieldConstant.MODULAR, ""));
            //服务名称
            apiMap.put("service_name", MapUtils.getString(apiInfo, ApiInfoFieldConstant.SERVICE_NAME, ""));
            //服务方法
            apiMap.put("service_method_name", MapUtils.getString(apiInfo, ApiInfoFieldConstant.METHOD_NAME, ""));
            //状态，代表服务是否在用，1在用，0不在用
            apiMap.put("service_status", MapUtils.getIntValue(apiInfo, ApiInfoFieldConstant.SERVICE_STATUS, 1));
            //版本，服务版本，如v1、v2
            apiMap.put("service_version", MapUtils.getString(apiInfo, ApiInfoFieldConstant.VERSION, "v1"));
            //是否登录验证，控制服务调用是否需要已登录，1是，0否
            apiMap.put("is_check_login", MapUtils.getIntValue(apiInfo, ApiInfoFieldConstant.IS_LOGIN, 1));
            //是否记录日志，控制服务是否记录日志，1是，0否
            apiMap.put("is_log", MapUtils.getIntValue(apiInfo, ApiInfoFieldConstant.IS_LOG, 0));
            //支持终端类型，支持的终端类型：PC/MOBILE/WX，支持多种终端采用逗号分隔
            apiMap.put("service_terminal", MapUtils.getString(apiInfo, ApiInfoFieldConstant.SERVICE_TERMINAL, ""));
            Map<String, Object> apiInfoOld = serviceListCtrlDao.getApiInfo(MapUtils.getIntValue(apiInfo, ApiInfoFieldConstant.SERVICE_ID, -1));
            if (apiInfoOld != null) {
                serviceListCtrlDao.modApi(MapUtils.getIntValue(apiInfo, ApiInfoFieldConstant.SERVICE_ID, -1), apiMap);
            } else {
                serviceListCtrlDao.addApi(apiMap);
            }
        }
        return responseBean;
    }

    /**
     * 数据库同步api到缓存
     *
     * @param requestBean
     * @param httpServletRequest
     * @return
     */
    public ResponseBean synApiDbToCache(RequestBean requestBean, HttpServletRequest httpServletRequest) {
        ResponseBean responseBean = requestBean.getResponseBean();
        List<Map<String, Object>> apiInfoList = serviceListCtrlDao.getApiInfoList();
        for (Map<String, Object> apiInfo : apiInfoList) {
            Map<String, String> apiMap = new HashMap<>();
            //服务URI
            String apiUri = MapUtils.getString(apiInfo, "service_uri", "");
            if (apiUri.length() == 0) {
                continue;
            }
            apiMap.put(ApiInfoFieldConstant.SERVICE_ID, MapUtils.getString(apiInfo, "service_id", ""));
            //服务URI
            apiMap.put(ApiInfoFieldConstant.SERVICE_URI, apiUri);
            //服务URL
            apiMap.put(ApiInfoFieldConstant.URL, MapUtils.getString(apiInfo, "service_url", ""));
            //服务模块
            apiMap.put(ApiInfoFieldConstant.MODULAR, MapUtils.getString(apiInfo, "servcie_modular", ""));
            //服务名称
            apiMap.put(ApiInfoFieldConstant.SERVICE_NAME, MapUtils.getString(apiInfo, "service_name", ""));
            //服务方法
            apiMap.put(ApiInfoFieldConstant.METHOD_NAME, MapUtils.getString(apiInfo, "service_method_name", ""));
            //状态，代表服务是否在用，1在用，0不在用
            apiMap.put(ApiInfoFieldConstant.SERVICE_STATUS, MapUtils.getString(apiInfo, "service_status", "1"));
            //版本，服务版本，如v1、v2
            apiMap.put(ApiInfoFieldConstant.VERSION, MapUtils.getString(apiInfo, "service_version", "v1"));
            //是否登录验证，控制服务调用是否需要已登录，1是，0否
            apiMap.put(ApiInfoFieldConstant.IS_LOGIN, MapUtils.getString(apiInfo, "is_check_login", "1"));
            //是否记录日志，控制服务是否记录日志，1是，0否
            apiMap.put(ApiInfoFieldConstant.IS_LOG, MapUtils.getString(apiInfo, "is_log", "0"));
            //支持终端类型，支持的终端类型：PC/MOBILE/WX，支持多种终端采用逗号分隔
            apiMap.put(ApiInfoFieldConstant.SERVICE_TERMINAL, MapUtils.getString(apiInfo, "service_terminal", ""));
            redisUtil.hmSetWithStrKey(RedisKeyConstant.API_INFO_PREFIX + apiUri, apiMap);
        }
        return responseBean;
    }

    /**
     * api缓存清空
     * @param requestBean
     * @param httpServletRequest
     * @return
     */
    public ResponseBean delCache(RequestBean requestBean, HttpServletRequest httpServletRequest) {
        ResponseBean responseBean = requestBean.getResponseBean();
        List<String> apiList = redisUtil.getKey(RedisKeyConstant.API_INFO_PREFIX + "*");
        for (String apiKey : apiList) {
            if (apiKey.equalsIgnoreCase("api:list:/api/v1/UserLoginService/login") ||
                    apiKey.equalsIgnoreCase("api:list:/api/v1/AdminLoginService/login") ||
                    apiKey.equalsIgnoreCase("api:list:/api/v1/ServiceListCtrlService/synApiCacheToDb") ||
                    apiKey.equalsIgnoreCase("api:list:/api/v1/ServiceListCtrlService/synApiDbToCache")) {
                continue;
            }
            redisUtil.del(apiKey);
            List<String> test = redisUtil.getKey(RedisKeyConstant.API_INFO_PREFIX + "*");
        }
        return responseBean;
    }

    /**
     * 查询api列表
     * @param requestBean
     * @param httpServletRequest
     * @return
     */
    public ResponseBean queryServiceList(RequestBean requestBean,HttpServletRequest httpServletRequest) {
        int currentPage = requestBean.getRequestParamInteger("currentPage", 1);
        int pageSize = requestBean.getRequestParamInteger("pageSize", 10);
        String serviceName = requestBean.getRequestParamString("service_name");
        Integer serviceStatus = requestBean.getRequestParamInteger("service_status");
        Map<String, Object> serviceMap = new HashMap<>();
        serviceMap.put("serviceName",serviceName);
        serviceMap.put("serviceStatus",serviceStatus);
        ResponseBean responseBean = requestBean.getResponseBean();
        Page<Map<String, Object>> page = new Page<>(currentPage, pageSize);
        page.setRecords(serviceListCtrlDao.queryServiceList(page,serviceMap));
        responseBean.addResultPageItem("serviceList", page);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 新增服务api
     * @param requestBean
     * @param httpServletRequest
     * @return
     */
    public ResponseBean addServiceList(RequestBean requestBean,HttpServletRequest httpServletRequest) {
        Map<String, Object> serviceMap = getParam(requestBean);
        ResponseBean responseBean = requestBean.getResponseBean();
        int num = serviceListCtrlDao.addServiceList(serviceMap);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 修改服务接口api
     * @param requestBean
     * @return
     */
    public ResponseBean modServiceList(RequestBean requestBean,HttpServletRequest httpServletRequest) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Map<String, Object> serviceMap = getParam(requestBean);
        int num = serviceListCtrlDao.modServiceList(serviceMap);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 删除服务接口api
     * @param requestBean
     * @return
     */
    public ResponseBean delServiceList(RequestBean requestBean,HttpServletRequest httpServletRequest) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer serviceId = requestBean.getRequestParamInteger("service_id");
        int num = serviceListCtrlDao.delServiceList(serviceId);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 获取参数
     * @param requestBean
     * @return
     */
    private Map<String, Object> getParam(RequestBean requestBean){
        String[][] params = new String[][]{{"service_id", ""},
                {"service_uri", ""},
                {"service_name", ""},
                {"service_method_name", ""},
                {"service_status", "1"},
                {"service_version", ""},
                {"service_url", ""},
                {"servcie_modular", ""},
                {"is_check_login", "1"},
                {"is_log", "1"},
                {"service_terminal", ""},
                {"service_desc", ""}
    };
        Map<String, Object> serviceMap = new HashMap<>();
        for (String[] param : params) {
            Object value = requestBean.getRequestParam(param[0]);
            if (value == null) {
                serviceMap.put(param[0], param[1]);
            } else {
                serviceMap.put(param[0], requestBean.getRequestParam(param[0]));
            }
        }
        return serviceMap;
    }
}
